package com.cjst.config;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;

import com.alibaba.druid.util.StringUtils;
import com.cjst.pojo.sys.SysMenu;
import com.cjst.pojo.sys.SysRelation;
import com.cjst.pojo.sys.SysRole;
import com.cjst.pojo.sys.SysUser;
import com.cjst.service.sys.SysMenuService;
import com.cjst.service.sys.SysRelationService;
import com.cjst.service.sys.SysRoleService;
import com.cjst.service.sys.SysUserService;
import com.cjst.sql.C;
import com.cjst.sql.Method;
import com.cjst.sql.WherePrams;

/**
 * 权限配置
 */
public class MyShiroRealm extends AuthorizingRealm {
    @Resource
    private SysUserService userService;
    @Resource
    private SysRoleService roleService;   
    @Resource
    private SysRelationService relationService;
    @Resource
    private SysMenuService menuService;
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        System.out.println("权限配置-->MyShiroRealm.doGetAuthorizationInfo()");
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        SysUser userInfo  = (SysUser)principals.getPrimaryPrincipal();
        String roleId = userInfo.getRoleId();
        if(!StringUtils.isEmpty(roleId)) {
        	SysRole role = roleService.get(roleId);
        	if(role!=null) {
        		if("1".equals(role.getType())) {
        			authorizationInfo.addRole(role.getName());
        			List<Map<String, Object>> menus = menuService.getMenuMap(null, null);
        			for (Map<String, Object> map : menus) {
        				authorizationInfo.addStringPermission((String)map.get("code"));
					}
        		}else {
        			authorizationInfo.addRole(role.getName());
            		//查询角色拥有的权限
            		WherePrams prams = Method.where("roleid", C.EQ, roleId);
            		List<SysRelation> relations = relationService.list(prams);
            		for (SysRelation sysRelation : relations) {
    					String menuId = sysRelation.getMenuid();
    					if(!StringUtils.isEmpty(menuId)) {
    						SysMenu menu = menuService.get(menuId);
    						authorizationInfo.addStringPermission(menu.getCode());
    					}
    				}
        		}
        		
        	}
        }

        return authorizationInfo;
    }

    /*主要是用来进行身份认证的，也就是说验证用户输入的账号和密码是否正确。*/
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token)
            throws AuthenticationException {
        System.out.println("MyShiroRealm.doGetAuthenticationInfo()");
        //获取用户的输入的账号.
        String username = (String)token.getPrincipal();
        System.out.println(token.getCredentials());
        //通过username从数据库中查找 User对象，如果找到，没找到.
        //实际项目中，这里可以根据实际情况做缓存，如果不做，Shiro自己也是有时间间隔机制，2分钟内不会重复执行该方法
        WherePrams prams = Method.where("userName", C.EQ, username);
        SysUser userInfo = userService.get(prams);
        System.out.println("----->>userInfo="+userInfo);
        if(userInfo == null){
            return null;
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(
                userInfo, //用户名
                userInfo.getPassword(), //密码
                ByteSource.Util.bytes(userInfo.getSalt()),//salt=username+salt
                getName()  //realm name
        );
        return authenticationInfo;
    }

}
